package com.hsck.order.kds.base.utils

import android.content.ClipData
import android.content.ClipDescription
import android.content.ClipboardManager
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.os.Build
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.view.Display
import android.view.LayoutInflater
import android.view.View
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.ScaleAnimation
import android.view.animation.TranslateAnimation
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.annotation.DimenRes
import androidx.annotation.LayoutRes
import androidx.core.content.ContextCompat
import com.hsck.order.kds.AppApplication
import com.hsck.order.kds.base.isnoam.log.XLog
import kotlin.math.roundToInt

object UIHelper {

    fun getDensity(context: Context): Float {
        val dm = context.resources.displayMetrics
        return dm.density
    }

    fun hasData(vararg edits: TextView): Boolean {
        for (editText in edits) {
            if (!TextUtils.isEmpty(editText.text.toString().trim { it <= ' ' })) {
                return true
            }
        }
        return false
    }

    fun hasEmpty(edits: List<TextView>): Boolean {
        for (editText in edits) {
            if (TextUtils.isEmpty(editText.text.toString().trim { it <= ' ' })) {
                return true
            }
        }
        return false
    }

    fun hasEmpty(vararg edits: TextView): Boolean {
        for (editText in edits) {
            if (TextUtils.isEmpty(editText.text.toString().trim { it <= ' ' })) {
                return true
            }
        }
        return false
    }

    fun hasEmpty(edits: Array<ImageView>): Boolean {
        for (imageView in edits) {
            if (TextUtils.isEmpty(imageView.tag.toString().trim { it <= ' ' })) {
                return true
            }
        }
        return false
    }

    fun setRightDrawable(textView: TextView, draw: Int) {
        val drawable = getDrawable(draw)
        try {
            assert(drawable != null)
            drawable!!.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
            textView.setCompoundDrawables(null, null, drawable, null)
        } catch (e: NullPointerException) {
            e.printStackTrace()
        }
    }

    fun setTopDrawable(textView: TextView, draw: Int) {
        val drawable = getDrawable(draw)
        try {
            assert(drawable != null)
            drawable!!.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
            textView.setCompoundDrawables(null, drawable, null, null)
        } catch (e: NullPointerException) {
            e.printStackTrace()
        }
    }

    fun setLeftDrawable(textView: TextView, draw: Int) {
        val drawable = getDrawable(draw)
        try {
            assert(drawable != null)
            drawable!!.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
            textView.setCompoundDrawables(drawable, null, null, null)
        } catch (e: NullPointerException) {
            e.printStackTrace()
        }
    }

    fun setLeftDrawable(textView: TextView, drawable: Drawable?) {
        try {
            assert(drawable != null)
            drawable!!.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
            textView.setCompoundDrawables(drawable, null, null, null)
        } catch (e: NullPointerException) {
            e.printStackTrace()
        }
    }

    /**
     * 资源ID获取String
     */
    fun getString(stringId: Int): String {
        return AppApplication.context.getString(stringId)
    }

    fun getString(stringId: Int, vararg formatArgs: Any?): String {
        return AppApplication.context.getString(stringId, *formatArgs)
    }

    /**
     * 获取尺寸
     */
    fun getDimension(@DimenRes dimenRes: Int): Int {
        return AppApplication.context.resources.getDimension(dimenRes).roundToInt()
    }

    /**
     * 获取颜色
     */
    fun getColor(@ColorRes color: Int): Int {
        return ContextCompat.getColor(AppApplication.context, color)
    }


    /**
     * 获取Drawable
     */
    fun getDrawable(drawable: Int): Drawable? {
        return ContextCompat.getDrawable(AppApplication.context, drawable)
    }

    fun inflaterLayout(context: Context?, @LayoutRes layoutRes: Int): View {
        val inflater = LayoutInflater.from(context)
        return inflater.inflate(layoutRes, null)
    }


    /**
     * 圆角Drawable
     *
     * @param radius 圆角
     * @param color  填充颜色
     */
    fun getShapeDrawable(radius: Int, @ColorInt color: Int): GradientDrawable {
        val gd = GradientDrawable()
        gd.setColor(color)
        gd.cornerRadius = radius.toFloat()
        return gd
    }

    fun clipContent(content: String?) {
        val cm =
            AppApplication.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        val mClipData = ClipData.newPlainText("Label", content)
        cm.setPrimaryClip(mClipData)
    }

    val clipContent: String
        get() {
            val cm =
                AppApplication.context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            if (cm != null && cm.primaryClipDescription!!.hasMimeType(
                    ClipDescription.MIMETYPE_TEXT_PLAIN
                )
            ) {
                val cdText = cm.primaryClip
                val item = cdText!!.getItemAt(0)
                return item.text.toString()
            }
            return ""
        }
    val packageName: String
        /**
         * 得到应用程序的包名
         *
         * @return
         */
        get() = AppApplication.context.packageName

    /**
     * [获取应用程序版本名称信息]
     *
     * @param context
     * @return 当前应用的版本名称
     */
    @Synchronized
    fun getVersionName(): String? {
        try {
            val packageManager = AppApplication.context.packageManager
            val packageInfo = packageManager.getPackageInfo(
                AppApplication.context.packageName, 0
            )
            return packageInfo.versionName
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    val appVersionName: String
        /**
         * 返回当前程序版本名
         */
        get() {
            var versionName = ""
            try {
                val pm: PackageManager = AppApplication.context.packageManager
                val pi: PackageInfo = pm.getPackageInfo(AppApplication.context.packageName, 0)
                versionName = pi.versionName
                if (versionName == null || versionName.length <= 0) {
                    return ""
                }
            } catch (e: Exception) {
                XLog.e("VersionInfo Exception", e)
            }
            return versionName
        }

    fun ScaleUpDowm(view: View) {
        val animation = ScaleAnimation(1.0f, 1.0f, 0.0f, 1.0f)
        animation.repeatCount = -1
        animation.repeatMode = Animation.RESTART
        animation.interpolator = LinearInterpolator()
        animation.duration = 1200
        view.startAnimation(animation)
    }

    /**
     * @param str                  要修改的字符串
     * @param absoluteSizeSpan1    修改特定位置字符串的字号
     * @param foregroundColorSpan1 修改特定位置字符串的颜色
     * @param i                    要修改的字符串的起始位置
     * @param j                    要修改的字符串的结束位置
     * @return
     */
    fun setTextViewContentStyle(
        str: String?,
        absoluteSizeSpan1: AbsoluteSizeSpan?,
        foregroundColorSpan1: ForegroundColorSpan?,
        i: Int,
        j: Int,
    ): CharSequence {
        // Auto-generated method stub
        val spStr = SpannableString(str)
        if (foregroundColorSpan1 != null) {
            spStr.setSpan(
                foregroundColorSpan1, i, j, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
        if (absoluteSizeSpan1 != null) {
            spStr.setSpan(
                absoluteSizeSpan1, i, j, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
        return spStr
    }

    /**
     * @param str                  要修改的字符串
     * @param absoluteSizeSpan1    修改特定位置字符串的字号
     * @param foregroundColorSpan1 修改特定位置字符串的颜色
     * @param i                    要修改的字符串的起始位置
     * @param j                    要修改的字符串的结束位置
     * @return
     */
    fun setTextViewContentStyle(
        str: String?,
        absoluteSizeSpan1: AbsoluteSizeSpan?,
        foregroundColorSpan1: ForegroundColorSpan?,
        i: Int,
        j: Int,
        url: String?,
    ): CharSequence {
        // Auto-generated method stub
        val spStr = SpannableString(str)
        if (foregroundColorSpan1 != null) {
            spStr.setSpan(
                foregroundColorSpan1, i, j, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
        if (absoluteSizeSpan1 != null) {
            spStr.setSpan(
                absoluteSizeSpan1, i, j, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
        return spStr
    }

    /**
     * 禁用7.0（23）以上显示大小改变和文字大小
     */
    fun disabledDisplayDpiChange(res: Resources): Resources {
        val newConfig = res.configuration
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //字体非默认值
            if (res.configuration.fontScale != 1f) {
                newConfig.fontScale = 1f
            }
            newConfig.densityDpi = defaultDisplayDensity
            res.updateConfiguration(newConfig, res.displayMetrics)
        } else {
            //字体非默认值
            if (res.configuration.fontScale != 1f) {
                newConfig.fontScale = 1f //设置默认
                res.updateConfiguration(newConfig, res.displayMetrics)
            }
        }
        return res
    }

    val defaultDisplayDensity: Int
        /**
         * 获取手机出厂时默认的densityDpi
         */
        get() = try {
            val aClass = Class.forName("android.view.WindowManagerGlobal")
            val method = aClass.getMethod("getWindowManagerService")
            method.isAccessible = true
            val iwm = method.invoke(aClass)
            val getInitialDisplayDensity = iwm.javaClass.getMethod(
                "getInitialDisplayDensity", Int::class.javaPrimitiveType
            )
            getInitialDisplayDensity.isAccessible = true
            val densityDpi = getInitialDisplayDensity.invoke(iwm, Display.DEFAULT_DISPLAY)
            densityDpi as Int
        } catch (e: Exception) {
            e.printStackTrace()
            -1
        }

    /**
     * by mos on 2018.01.12
     * func:view转bitmap
     */
    fun convertViewToBitmap(view: View): Bitmap {
        view.measure(
            View.MeasureSpec.makeMeasureSpec(
                0, View.MeasureSpec.UNSPECIFIED
            ), View.MeasureSpec.makeMeasureSpec(
                0, View.MeasureSpec.UNSPECIFIED
            )
        )
        view.layout(0, 0, view.measuredWidth, view.measuredHeight)
        view.buildDrawingCache()
        return view.drawingCache
    }

    fun gone(view: View, time: Long?) {
        if (view.visibility != View.GONE) {
            val hideAnim = TranslateAnimation(
                Animation.RELATIVE_TO_SELF,
                0.0f,
                Animation.RELATIVE_TO_SELF,
                1.0f,
                Animation.RELATIVE_TO_SELF,
                0.0f,
                Animation.RELATIVE_TO_SELF,
                0.0f
            )
            hideAnim.duration = time!!
            view.startAnimation(hideAnim)
            view.visibility = View.GONE
        }
    }

    fun visible(view: View, time: Long?) {
        if (view.visibility != View.VISIBLE) {
            val showAnim = TranslateAnimation(
                Animation.RELATIVE_TO_SELF,
                1.0f,
                Animation.RELATIVE_TO_SELF,
                0.0f,
                Animation.RELATIVE_TO_SELF,
                0.0f,
                Animation.RELATIVE_TO_SELF,
                0.0f
            )
            showAnim.duration = time!!
            view.startAnimation(showAnim)
            view.visibility = View.VISIBLE
        }
    }
}